// 全局变量
let userInfo = null;
let stompClient = null;
let roomId = null;
let gameState = null;
let boardState = [];
let myColor = null;
let currentTurn = null;
let isMyTurn = false;
let gameStartTime = null;
let gameTimer = null;
let isGameOver = false;
let lastMovePosition = null;

// 游戏常量
const BOARD_SIZE = 15;
const EMPTY = 0;
const BLACK = 1;
const WHITE = 2;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializePage();
});

// 初始化页面
async function initializePage() {
    // 检查登录状态
    if (!checkLoginStatus()) {
        return;
    }
    
    // 获取房间ID
    roomId = getRoomIdFromUrl();
    if (!roomId) {
        alert('无效的游戏房间');
        window.location.href = 'hall.html';
        return;
    }
    
    // 初始化棋盘
    initializeBoard();
    
    // 建立WebSocket连接
    connectWebSocket();
    
    // 加载游戏房间信息
    await loadGameRoom();
    
    // 启动定期状态检查
    startPeriodicStateCheck();
}

// 检查登录状态
function checkLoginStatus() {
    const token = localStorage.getItem('token');
    const userInfoStr = localStorage.getItem('userInfo');
    
    if (!token || !userInfoStr) {
        window.location.href = 'login.html';
        return false;
    }
    
    try {
        userInfo = JSON.parse(userInfoStr);
        return true;
    } catch (error) {
        console.error('解析用户信息失败:', error);
        localStorage.clear();
        window.location.href = 'login.html';
        return false;
    }
}

// 从URL获取房间ID
function getRoomIdFromUrl() {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get('roomId');
}

// 初始化棋盘
function initializeBoard() {
    const gameBoard = document.getElementById('gameBoard');
    gameBoard.innerHTML = '';
    
    // 初始化棋盘状态
    boardState = [];
    for (let i = 0; i < BOARD_SIZE; i++) {
        boardState[i] = [];
        for (let j = 0; j < BOARD_SIZE; j++) {
            boardState[i][j] = EMPTY;
        }
    }
    
    // 创建棋盘格子
    for (let row = 0; row < BOARD_SIZE; row++) {
        for (let col = 0; col < BOARD_SIZE; col++) {
            const cell = document.createElement('div');
            cell.className = 'board-cell';
            cell.dataset.row = row;
            cell.dataset.col = col;
            
            // 添加点击事件
            cell.addEventListener('click', () => handleCellClick(row, col));
            
            // 添加鼠标悬停效果
            cell.addEventListener('mouseenter', () => handleCellHover(row, col, true));
            cell.addEventListener('mouseleave', () => handleCellHover(row, col, false));
            
            gameBoard.appendChild(cell);
        }
    }
}

// 建立WebSocket连接
function connectWebSocket() {
    try {
        const token = localStorage.getItem('token');
        const socket = new SockJS('/websocket/gobang');
        stompClient = Stomp.over(socket);
        
        stompClient.debug = function(str) {
            console.log('STOMP: ' + str);
        };

        const headers = {
            'Authorization': `Bearer ${token}`
        };

        stompClient.connect(headers, function(frame) {
            console.log('WebSocket连接成功: ' + frame);
            updateConnectionStatus(true);
            
            // 订阅用户消息
            stompClient.subscribe(`/user/queue/messages`, function(message) {
                handleWebSocketMessage(JSON.parse(message.body));
            });
            
            // 请求游戏状态
            requestGameState();
            
        }, function(error) {
            console.error('WebSocket连接失败: ', error);
            updateConnectionStatus(false);
            setTimeout(connectWebSocket, 5000);
        });
    } catch (error) {
        console.error('WebSocket连接异常:', error);
        updateConnectionStatus(false);
    }
}

// 更新连接状态显示
function updateConnectionStatus(connected) {
    const textEl = document.getElementById('connectionText');
    const loadingEl = document.getElementById('connectionLoading');
    
    if (connected) {
        textEl.textContent = '✓ 已连接';
        loadingEl.style.display = 'none';
    } else {
        textEl.textContent = '⚠ 连接中断';
        loadingEl.style.display = 'inline-block';
    }
}

// 加载游戏房间信息
async function loadGameRoom() {
    try {
        const token = localStorage.getItem('token');
        const response = await fetch(`/api/game/room/${roomId}`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });

        const result = await response.json();
        
        if (result.code === '1000') {
            gameState = result.data;
            updateGameDisplay();
        } else {
            console.error('加载游戏房间失败:', result.message);
            alert('加载游戏房间失败');
            window.location.href = 'hall.html';
        }
    } catch (error) {
        console.error('加载游戏房间异常:', error);
        alert('网络异常，无法加载游戏');
        window.location.href = 'hall.html';
    }
}

// 更新游戏显示
function updateGameDisplay() {
    if (!gameState) return;
    
    // 更新玩家信息
    document.getElementById('blackPlayerName').textContent = gameState.blackPlayer.username;
    document.getElementById('blackPlayerScore').textContent = `积分: ${gameState.blackPlayer.currentScore}`;
    document.getElementById('whitePlayerName').textContent = gameState.whitePlayer.username;
    document.getElementById('whitePlayerScore').textContent = `积分: ${gameState.whitePlayer.currentScore}`;
    
    // 确定我的颜色
    if (gameState.blackPlayer.id === userInfo.id) {
        myColor = BLACK;
        console.log('确定我的颜色: BLACK(黑棋)');
    } else if (gameState.whitePlayer.id === userInfo.id) {
        myColor = WHITE;
        console.log('确定我的颜色: WHITE(白棋)');
    }
    
    // 更新棋盘状态
    if (gameState.boardState) {
        boardState = gameState.boardState;
        renderBoard();
    }
    
    // 更新游戏状态
    updateTurnIndicator();
    updateGameControls();
}

// 更新回合指示器
function updateTurnIndicator() {
    const indicator = document.getElementById('turnIndicator');
    
    // 添加调试信息
    console.log('更新回合指示器 - 游戏状态:', gameState.gameStatus, '当前回合:', gameState.currentTurn, '我的颜色:', myColor === BLACK ? 'BLACK' : 'WHITE');
    
    // 更新页面上的调试信息
    updateDebugInfo();
    
    if (gameState.gameStatus === 'WAITING') {
        indicator.textContent = '等待游戏开始...';
        indicator.className = 'turn-indicator waiting';
        isMyTurn = false;
    } else if (gameState.gameStatus === 'PLAYING') {
        const currentPlayerColor = gameState.currentTurn;
        const isCurrentPlayerMe = (
            (currentPlayerColor === 'BLACK' && myColor === BLACK) ||
            (currentPlayerColor === 'WHITE' && myColor === WHITE)
        );
        
        // 添加更多调试信息
        console.log('当前应该下棋的颜色:', currentPlayerColor, '是否轮到我:', isCurrentPlayerMe);
        
        if (isCurrentPlayerMe) {
            indicator.textContent = '轮到您落子';
            indicator.className = 'turn-indicator my-turn';
            isMyTurn = true;
        } else {
            const currentPlayerName = currentPlayerColor === 'BLACK' 
                ? gameState.blackPlayer.username 
                : gameState.whitePlayer.username;
            indicator.textContent = `等待 ${currentPlayerName} 落子`;
            indicator.className = 'turn-indicator waiting';
            isMyTurn = false;
        }
        
        // 在页面上显示更详细的回合信息（用于调试）
        const turnDebugInfo = `当前回合: ${currentPlayerColor}棋`;
        console.log(turnDebugInfo);
        
        startGameTimer();
    } else if (gameState.gameStatus === 'FINISHED') {
        if (gameState.winnerId === userInfo.id) {
            indicator.textContent = '您获胜了！';
            indicator.className = 'turn-indicator';
        } else {
            indicator.textContent = '您失败了';
            indicator.className = 'turn-indicator waiting';
        }
        isMyTurn = false;
        isGameOver = true;
        stopGameTimer();
    }
}

// 更新调试信息显示
function updateDebugInfo() {
    const debugCurrentTurn = document.getElementById('debugCurrentTurn');
    const debugMyColor = document.getElementById('debugMyColor');
    const debugIsMyTurn = document.getElementById('debugIsMyTurn');
    const debugWebSocketStatus = document.getElementById('debugWebSocketStatus');
    const debugLastUpdate = document.getElementById('debugLastUpdate');
    
    if (debugCurrentTurn) {
        debugCurrentTurn.textContent = `当前回合: ${gameState.currentTurn || '未知'}`;
    }
    if (debugMyColor) {
        debugMyColor.textContent = `我的颜色: ${myColor === BLACK ? 'BLACK(黑)' : myColor === WHITE ? 'WHITE(白)' : '未确定'}`;
    }
    if (debugIsMyTurn) {
        debugIsMyTurn.textContent = `是否轮到我: ${isMyTurn ? '是' : '否'}`;
    }
    if (debugWebSocketStatus) {
        const status = stompClient?.connected ? '已连接' : '未连接';
        debugWebSocketStatus.textContent = `WebSocket: ${status}`;
    }
    if (debugLastUpdate) {
        debugLastUpdate.textContent = `最后更新: ${new Date().toLocaleTimeString()}`;
    }
}

// 更新游戏控制
function updateGameControls() {
    const surrenderBtn = document.getElementById('surrenderBtn');
    const backToHallBtn = document.getElementById('backToHallBtn');
    
    if (gameState.gameStatus === 'PLAYING') {
        surrenderBtn.style.display = 'block';
        backToHallBtn.style.display = 'none';
    } else {
        surrenderBtn.style.display = 'none';
        backToHallBtn.style.display = 'block';
    }
}

// 渲染棋盘
function renderBoard() {
    console.log('========== 开始渲染棋盘 ==========');
    console.log('当前本地棋盘状态:', boardState);
    console.log('最后落子位置:', lastMovePosition);
    
    // 统计当前棋盘上的棋子
    let currentPieceCount = 0;
    for (let i = 0; i < BOARD_SIZE; i++) {
        for (let j = 0; j < BOARD_SIZE; j++) {
            if (boardState[i] && boardState[i][j] !== EMPTY) {
                currentPieceCount++;
                console.log(`棋盘数据: [${i},${j}] = ${boardState[i][j] === BLACK ? 'BLACK' : 'WHITE'}`);
            }
        }
    }
    console.log('棋盘数据中总棋子数:', currentPieceCount);
    
    const gameBoard = document.getElementById('gameBoard');
    if (!gameBoard) {
        console.error('找不到游戏棋盘元素');
        return;
    }
    
    const cells = gameBoard.querySelectorAll('.board-cell');
    console.log('找到棋盘格子数量:', cells.length);
    
    let pieceCount = 0; // 统计棋子数量
    let renderedCount = 0; // 统计实际渲染的棋子数量
    
    cells.forEach((cell, index) => {
        const row = Math.floor(index / BOARD_SIZE);
        const col = index % BOARD_SIZE;
        
        // 清除现有棋子（包括预览棋子）
        const existingPieces = cell.querySelectorAll('.piece');
        existingPieces.forEach(p => p.remove());
        
        // 添加新棋子
        if (boardState[row] && boardState[row][col] !== EMPTY) {
            pieceCount++;
            
            const pieceEl = document.createElement('div');
            
            // 完全使用内联样式，确保可见性
            pieceEl.style.cssText = `
                width: 26px;
                height: 26px;
                border-radius: 50%;
                border: 2px solid #333;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
                flex-shrink: 0;
                display: block;
                ${boardState[row][col] === BLACK ? 'background-color: #000;' : 'background-color: #fff;'}
                ${lastMovePosition && lastMovePosition.row === row && lastMovePosition.col === col ? 
                  'border-color: #E74C3C; border-width: 3px;' : ''}
            `;
            
            // 设置类名以便调试
            pieceEl.className = `piece ${boardState[row][col] === BLACK ? 'black' : 'white'}`;
            if (lastMovePosition && lastMovePosition.row === row && lastMovePosition.col === col) {
                pieceEl.classList.add('last-move');
            }
            
            // 确保元素可见
            pieceEl.setAttribute('data-row', row);
            pieceEl.setAttribute('data-col', col);
            pieceEl.setAttribute('data-color', boardState[row][col] === BLACK ? 'black' : 'white');
            
            cell.appendChild(pieceEl);
            renderedCount++;
            
            console.log(`✓ 渲染棋子 [${row},${col}] - 颜色: ${boardState[row][col] === BLACK ? 'BLACK' : 'WHITE'}`);
        }
    });
    
    console.log('========== 渲染完成 ==========');
    console.log('数据中棋子数:', pieceCount, '实际渲染棋子数:', renderedCount);
    
    // 强制重绘和验证
    setTimeout(() => {
        const allPieces = gameBoard.querySelectorAll('.piece');
        console.log('渲染后验证 - DOM中棋子数量:', allPieces.length);
        
        allPieces.forEach((piece, index) => {
            const rect = piece.getBoundingClientRect();
            console.log(`DOM棋子 ${index}: 位置(${piece.getAttribute('data-row')},${piece.getAttribute('data-col')}), 大小: ${rect.width}x${rect.height}, 可见: ${rect.width > 0 && rect.height > 0}`);
        });
        
        // 强制重绘
        gameBoard.style.display = 'none';
        gameBoard.offsetHeight; // 触发重绘
        gameBoard.style.display = '';
        console.log('强制重绘完成');
    }, 50);
}

// 处理格子点击
function handleCellClick(row, col) {
    console.log('点击格子:', row, col, '是否轮到我:', isMyTurn, '游戏是否结束:', isGameOver, '格子状态:', boardState[row][col]);
    
    if (!isMyTurn || isGameOver || boardState[row][col] !== EMPTY) {
        console.log('无法落子 - 不是我的回合或游戏已结束或格子已占用');
        return;
    }
    
    // 发送落子请求
    console.log('发送落子请求:', row, col);
    makeMove(row, col);
}

// 处理格子悬停
function handleCellHover(row, col, isEnter) {
    if (!isMyTurn || isGameOver || boardState[row][col] !== EMPTY) {
        return;
    }
    
    const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
    
    if (isEnter) {
        // 显示预览棋子
        const previewPiece = document.createElement('div');
        previewPiece.className = 'piece preview';
        if (myColor === BLACK) {
            previewPiece.classList.add('black');
        } else {
            previewPiece.classList.add('white');
        }
        cell.appendChild(previewPiece);
    } else {
        // 移除预览棋子
        const previewPiece = cell.querySelector('.piece.preview');
        if (previewPiece) {
            previewPiece.remove();
        }
    }
}

// 发送落子请求
function makeMove(row, col) {
    console.log('准备发送落子请求 - 位置:', row, col, 'WebSocket状态:', stompClient?.connected);
    
    if (stompClient && stompClient.connected) {
        const moveMessage = {
            type: 'MAKE_MOVE',
            data: {
                roomId: roomId,
                row: row,
                col: col
            }
        };
        
        try {
            // 本地预更新：立即在界面上显示落子效果
            console.log('本地预更新：在位置', row, col, '放置', myColor === BLACK ? 'BLACK' : 'WHITE', '棋子');
            boardState[row][col] = myColor;
            lastMovePosition = { row: row, col: col };
            
            // 立即渲染，提供即时反馈
            renderBoard();
            
            // 暂时禁用点击，防止重复操作
            isMyTurn = false;
            updateTurnIndicator();
            
            stompClient.send('/app/game/move', {}, JSON.stringify(moveMessage));
            console.log('落子请求发送成功:', moveMessage);
        } catch (error) {
            console.error('发送落子请求失败:', error);
            
            // 如果发送失败，回滚本地更新
            console.log('发送失败，回滚本地更新');
            boardState[row][col] = EMPTY;
            lastMovePosition = null;
            renderBoard();
            isMyTurn = true;
            updateTurnIndicator();
            
            alert('发送落子请求失败，请重试');
        }
    } else {
        console.error('WebSocket未连接，无法发送落子请求');
        alert('网络连接异常，请刷新页面重试');
    }
}

// 请求游戏状态
function requestGameState() {
    if (stompClient && stompClient.connected) {
        const stateMessage = {
            type: 'REQUEST_GAME_STATE',
            data: {
                roomId: roomId
            }
        };
        
        stompClient.send('/app/game/state', {}, JSON.stringify(stateMessage));
        console.log('请求游戏状态:', stateMessage);
    }
}

// 处理WebSocket消息
function handleWebSocketMessage(message) {
    console.log('收到WebSocket消息:', message);
    
    switch (message.type) {
        case 'HEARTBEAT':
            sendHeartbeatResponse();
            break;
            
        case 'GAME_STATE_UPDATE':
            handleGameStateUpdate(message.data);
            break;
            
        case 'GAME_STATE_RESPONSE':
            handleGameStateResponse(message.data);
            break;
            
        case 'MOVE_RESPONSE':
            handleMoveResponse(message.data);
            break;
            
        case 'GAME_OVER':
            handleGameOver(message.data);
            break;
            
        case 'OPPONENT_OFFLINE':
            handleOpponentOffline(message.data);
            break;
            
        case 'ERROR_RESPONSE':
            handleErrorMessage(message.data);
            break;
            
        default:
            console.log('未处理的消息类型:', message.type);
    }
}

// 发送心跳响应
function sendHeartbeatResponse() {
    if (stompClient && stompClient.connected) {
        stompClient.send('/app/heartbeat', {}, JSON.stringify({
            type: 'HEARTBEAT_RESPONSE',
            data: {
                timestamp: Date.now()
            }
        }));
    }
}

// 处理游戏状态更新
function handleGameStateUpdate(data) {
    console.log('收到游戏状态更新:', data);
    
    if (data.roomId === roomId) {
        console.log('处理房间', roomId, '的游戏状态更新');
        
        // 记录更新前的状态
        const oldBoardState = JSON.parse(JSON.stringify(boardState));
        const oldTurn = gameState.currentTurn;
        
        // 优先使用服务器返回的完整棋盘状态
        if (data.boardState) {
            console.log('使用服务器提供的完整棋盘状态:', data.boardState);
            boardState = data.boardState;
        } else if (data.lastMove) {
            // 如果没有完整棋盘状态，只更新最后一步
            console.log('只有最后一步棋信息，增量更新:', data.lastMove);
            lastMovePosition = {
                row: data.lastMove.row,
                col: data.lastMove.col
            };
            
            // 更新棋盘状态
            const pieceColor = data.lastMove.color === 'BLACK' ? BLACK : WHITE;
            boardState[data.lastMove.row][data.lastMove.col] = pieceColor;
            console.log('在位置', data.lastMove.row, data.lastMove.col, '放置了', data.lastMove.color, '棋子');
        }
        
        // 更新最后落子位置（优先使用单独的lastMove字段）
        if (data.lastMove) {
            lastMovePosition = {
                row: data.lastMove.row,
                col: data.lastMove.col
            };
        }
        
        // 记录回合变化
        const newTurn = data.currentTurn;
        console.log('回合变化: ', oldTurn, ' -> ', newTurn);
        
        // 更新当前轮次
        gameState.currentTurn = data.currentTurn;
        gameState.gameStatus = data.gameStatus;
        gameState.moveCount = data.moveCount;
        
        // 强制重新渲染棋盘和更新UI
        console.log('强制重新渲染页面 - 更新后的棋盘状态:', boardState);
        renderBoard();
        updateTurnIndicator();
        updateGameControls();
        
        // 检查是否有实际变化
        const boardChanged = JSON.stringify(oldBoardState) !== JSON.stringify(boardState);
        const turnChanged = oldTurn !== newTurn;
        
        if (boardChanged || turnChanged) {
            console.log('检测到游戏状态变化 - 棋盘变化:', boardChanged, '回合变化:', turnChanged);
        } else {
            console.log('未检测到游戏状态变化，可能是重复消息');
        }
    } else {
        console.log('收到其他房间的游戏状态更新，忽略');
    }
}

// 处理游戏状态响应
function handleGameStateResponse(data) {
    console.log('收到游戏状态响应:', data);
    
    if (data.roomId === roomId) {
        // 更新完整的游戏状态
        gameState.gameStatus = data.gameStatus;
        gameState.currentTurn = data.currentTurn;
        gameState.moveCount = data.moveCount;
        
        // 更新棋盘状态
        if (data.boardState) {
            console.log('更新棋盘状态:', data.boardState);
            boardState = data.boardState;
        }
        
        // 更新最后落子位置
        if (data.lastMove) {
            console.log('更新最后一步棋:', data.lastMove);
            lastMovePosition = {
                row: data.lastMove.row,
                col: data.lastMove.col
            };
        }
        
        // 重新渲染棋盘和更新UI
        renderBoard();
        updateTurnIndicator();
        updateGameControls();
    }
}

// 处理落子响应
function handleMoveResponse(data) {
    console.log('收到落子响应:', data);
    
    if (data.roomId === roomId) {
        if (data.success) {
            console.log('落子成功');
            
            // 判断这是否是我的落子
            const isMyMove = data.playerId === userInfo.id || 
                           (data.color === 'BLACK' && myColor === BLACK) ||
                           (data.color === 'WHITE' && myColor === WHITE);
            
            console.log('这是我的落子吗?', isMyMove, '落子颜色:', data.color, '我的颜色:', myColor === BLACK ? 'BLACK' : 'WHITE');
            
            // 记录更新前的棋盘状态
            const oldBoardState = JSON.parse(JSON.stringify(boardState));
            
            // 更新棋盘状态
            if (data.row !== undefined && data.col !== undefined && data.color) {
                const pieceColor = data.color === 'BLACK' ? BLACK : WHITE;
                
                console.log('准备更新棋盘位置:', data.row, data.col, '原值:', boardState[data.row] ? boardState[data.row][data.col] : 'undefined', '新值:', pieceColor);
                
                boardState[data.row][data.col] = pieceColor;
                
                lastMovePosition = {
                    row: data.row,
                    col: data.col
                };
                
                console.log('✓ 在位置', data.row, data.col, '放置了', data.color, '棋子');
                console.log('更新后的棋盘状态:', boardState);
            } else {
                console.warn('MOVE_RESPONSE中缺少位置或颜色信息:', data);
            }
            
            // 更新游戏状态
            if (data.nextTurn) {
                gameState.currentTurn = data.nextTurn;
            } else if (data.color) {
                // 如果没有提供下一回合信息，手动切换
                gameState.currentTurn = data.color === 'BLACK' ? 'WHITE' : 'BLACK';
            }
            
            // 增加步数
            gameState.moveCount = (gameState.moveCount || 0) + 1;
            
            // 如果是我的落子，确认本地预更新是否正确
            if (isMyMove) {
                console.log('确认我的落子成功，本地预更新正确');
                // 本地预更新应该已经是正确的，直接更新回合状态
                isMyTurn = false;
            } else {
                console.log('这是对方的落子，更新页面显示对方棋子');
                // 对方落子，检查是否轮到我
                const isNowMyTurn = (
                    (gameState.currentTurn === 'BLACK' && myColor === BLACK) ||
                    (gameState.currentTurn === 'WHITE' && myColor === WHITE)
                );
                isMyTurn = isNowMyTurn;
            }
            
            // 立即重新渲染页面
            renderBoard();
            updateTurnIndicator();
            updateGameControls();
            
        } else {
            console.error('落子失败:', data.errorMessage);
            
            // 只有当这是我的落子失败时，才回滚本地预更新
            const isMyMove = data.playerId === userInfo.id || 
                           (data.color === 'BLACK' && myColor === BLACK) ||
                           (data.color === 'WHITE' && myColor === WHITE);
            
            if (isMyMove) {
                console.log('我的落子失败，回滚本地预更新');
                if (data.row !== undefined && data.col !== undefined) {
                    boardState[data.row][data.col] = EMPTY;
                    lastMovePosition = null;
                }
                
                // 恢复我的回合状态
                isMyTurn = true;
                
                // 重新渲染页面
                renderBoard();
                updateTurnIndicator();
                
                alert(data.errorMessage || '落子失败');
            }
        }
    }
}

// 处理游戏结束
function handleGameOver(data) {
    if (data.roomId === roomId) {
        console.log('游戏结束:', data);
        isGameOver = true;
        stopGameTimer();
        
        // 更新游戏状态
        gameState.gameStatus = 'FINISHED';
        gameState.winnerId = data.winnerId;
        
        // 显示游戏结果
        showGameResult(data);
        
        // 更新UI
        updateTurnIndicator();
        updateGameControls();
    }
}

// 显示游戏结果
function showGameResult(data) {
    const overlay = document.getElementById('gameResultOverlay');
    const title = document.getElementById('resultTitle');
    const scoreChange = document.getElementById('scoreChange');
    const currentScore = document.getElementById('currentScore');
    
    // 前端写死积分规则：赢了+5分，输了-3分
    let scoreChangeValue;
    let newScoreValue;
    
    if (data.winnerId === userInfo.id) {
        // 玩家获胜
        title.textContent = '🎉 你赢了！';
        title.className = 'result-title result-win';
        scoreChangeValue = 5;
        scoreChange.textContent = `+${scoreChangeValue}分`;
        scoreChange.className = 'score-change score-positive';
    } else {
        // 玩家失败
        title.textContent = '😔 你输了';
        title.className = 'result-title result-lose';
        scoreChangeValue = -3;
        scoreChange.textContent = `${scoreChangeValue}分`;
        scoreChange.className = 'score-change score-negative';
    }
    
    // 根据用户当前积分计算新积分
    const currentUserScore = userInfo.currentScore || 0;
    newScoreValue = currentUserScore + scoreChangeValue;
    
    // 确保积分不为负数，最低为0分
    newScoreValue = Math.max(0, newScoreValue);
    
    currentScore.textContent = `当前积分：${newScoreValue}`;
    overlay.style.display = 'flex';
    
    // 更新用户信息
    userInfo.currentScore = newScoreValue;
    localStorage.setItem('userInfo', JSON.stringify(userInfo));
}

// 处理对手离线
function handleOpponentOffline(data) {
    if (data.roomId === roomId) {
        alert(`对手 ${data.opponentUsername} 已离线，请等待重连或选择返回大厅`);
    }
}

// 处理错误消息
function handleErrorMessage(data) {
    console.error('游戏错误:', data);
    alert(data.errorMessage || '发生错误');
}

// 认输
async function surrender() {
    if (!confirm('确定要认输吗？')) {
        return;
    }
    
    try {
        const token = localStorage.getItem('token');
        const response = await fetch('/api/game/surrender', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                roomId: roomId,
                userId: userInfo.id
            })
        });

        const result = await response.json();
        
        if (result.code === '1000') {
            console.log('认输成功');
            // 游戏结束会通过WebSocket消息通知
        } else {
            console.error('认输失败:', result.message);
            alert('认输失败，请重试');
        }
    } catch (error) {
        console.error('认输异常:', error);
        alert('网络异常，请重试');
    }
}

// 返回大厅
function backToHall() {
    if (stompClient && stompClient.connected) {
        stompClient.disconnect();
    }
    window.location.href = 'hall.html';
}

// 开始游戏计时器
function startGameTimer() {
    if (!gameStartTime) {
        gameStartTime = Date.now();
    }
    
    if (!gameTimer) {
        gameTimer = setInterval(() => {
            const elapsed = Math.floor((Date.now() - gameStartTime) / 1000);
            const minutes = Math.floor(elapsed / 60);
            const seconds = elapsed % 60;
            document.getElementById('gameTimer').textContent = 
                `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }, 1000);
    }
}

// 停止游戏计时器
function stopGameTimer() {
    if (gameTimer) {
        clearInterval(gameTimer);
        gameTimer = null;
    }
}

// 定期状态检查
let stateCheckInterval = null;

function startPeriodicStateCheck() {
    // 每5秒检查一次游戏状态
    stateCheckInterval = setInterval(() => {
        if (gameState && gameState.gameStatus === 'PLAYING' && stompClient && stompClient.connected) {
            console.log('定期检查游戏状态');
            requestGameState();
        }
    }, 5000);
    
    console.log('启动定期状态检查');
}

function stopPeriodicStateCheck() {
    if (stateCheckInterval) {
        clearInterval(stateCheckInterval);
        stateCheckInterval = null;
        console.log('停止定期状态检查');
    }
}

// 页面卸载时清理资源
window.addEventListener('beforeunload', function() {
    if (stompClient && stompClient.connected) {
        stompClient.disconnect();
    }
    if (gameTimer) {
        clearInterval(gameTimer);
    }
    stopPeriodicStateCheck();
});

// 手动刷新游戏状态
function refreshGameState() {
    console.log('用户手动刷新游戏状态');
    
    if (stompClient && stompClient.connected) {
        requestGameState();
        updateDebugInfo();
        alert('已请求刷新游戏状态');
    } else {
        alert('WebSocket未连接，正在尝试重新连接...');
        connectWebSocket();
    }
} 